<template>
  <div class="_wz_insuranceAdd">
    <Form ref="formAdd" :model="formData" label-position="right" :label-width="100" :rules="ruleValidate">
      <Card dis-hover style="margin:0 0 10px 0;">
        <p slot="title">车辆选择</p>
        <Row>
          <i-col span="24">
            <i-col span="8">
              <FormItem label="保险车型" prop="insuranceModelType">
                <i-select v-model.number="formData.insuranceModelType" filterable placeholder="请选择保险车型" :label-in-value="true" @on-change="insuranceModelTypeFun" :disabled="!!selectData.id">
                  <Option :value="1">运输车辆</Option>
                  <Option :value="2">货运挂车</Option>
                </i-select>
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="保险车辆" prop="refVehicleTrailerUuid">
                <i-select v-model="formData.refVehicleTrailerUuid" filterable placeholder="请选择保险车辆" :label-in-value="true" clearable @on-change="insuranceVehicleTrailerPlateNoFun" :disabled="!!selectData.id">
                  <Option v-if="formData.insuranceModelType == 1" v-for="item in carList" :value="item.uuid" :key="item.uuid">{{item.carPlateNo}}</Option>
                  <Option v-if="formData.insuranceModelType == 2" v-for="item in carList" :value="item.uuid" :key="item.uuid">{{item.trailerPlateNo}}</Option>
                </i-select>
              </FormItem>
            </i-col>
          </i-col>
        </Row>
      </Card>
      <vehicleBriefly :vehicleBrieflyData="vehicleBrieflyData"></vehicleBriefly>
      <Card dis-hover style="height:100%;overflow: hidden;">
        <Row>
          <i-col span="24">
            <i-col span="8">
              <FormItem label="车主业户" prop="insuranceVehicleTrailerOwnerName">
                <i-input v-model="formData.insuranceVehicleTrailerOwnerName" placeholder="请填写车主业户" clearable />
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="联系电话" prop="insuranceVehicleTrailerOwnerPhone">
                <i-input v-model="formData.insuranceVehicleTrailerOwnerPhone" placeholder="请填写联系电话" clearable />
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="登记人" prop="insuranceRegistrantName">
                <i-input v-model="formData.insuranceRegistrantName" placeholder="请填写登记人" clearable />
              </FormItem>
            </i-col>
          </i-col>
          <i-col span="24">
            <i-col span="8">
              <FormItem label="保险公司" prop="insuranceCompanyValue">
                <Select v-model="formData.insuranceCompanyValue"  filterable allow-create @on-create="insuranceCompanyFun" placeholder="请选择投保公司" clearable >
                  <Option v-for="item in insuranceCompany" :value="item.value" :key="item.value">{{ item.value }}</Option>
                </Select>
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="保险项目" prop="insuranceTypeValue">
                <Select v-model="formData.insuranceTypeValue"  filterable allow-create @on-create="additionalInsuranceFun" placeholder="请选择保险项" clearable >
                  <Option v-for="item in insuranceType" :value="item.value" :key="item.value">{{ item.value }}</Option>
                </Select>
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="办理时间" prop="wzInsuranceDate">
                <DatePicker type="date" placeholder="请选择办理时间" style="width: 100%;" split-panels v-model="formData.wzInsuranceDate"></DatePicker>
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="生效日期" prop="wzInsuranceEffectiveDate">
                <DatePicker type="date" style="width: 100%;" split-panels :options="beginTime" v-model="formData.wzInsuranceEffectiveDate" placeholder="请选择生效日期" @on-change="onBeginTime"></DatePicker>
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="到期日期" prop="wzInsuranceExpireDate">
                <DatePicker type="date" style="width: 100%;" split-panels :options="endTime" v-model="formData.wzInsuranceExpireDate" placeholder="请选择到期日期" @on-change="onEndTime"></DatePicker>
              </FormItem>
            </i-col>


          </i-col>
          <i-col span="24">
            <i-col span="8">
              <FormItem label="保险全费" prop="insuranceFullFee">
                <i-input v-model="formData.insuranceFullFee" placeholder="请填写保险全费" clearable />
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="净费实收" prop="insuranceNetFee">
                <i-input v-model="formData.insuranceNetFee" placeholder="请填写净费实收" clearable />
              </FormItem>
            </i-col>
          </i-col>

          <i-col span="24">
            <i-col span="8">
              <FormItem label="提醒天数" prop="insuranceRemindDay">
                <i-input v-model.number="formData.insuranceRemindDay" placeholder="请填写提醒天数" clearable @on-change="wzInsuranceRemindDateFun"/>
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="提醒日期" prop="wzInsuranceRemindDate">
                <DatePicker type="date" v-model="formData.wzInsuranceRemindDate" placeholder="请选择提醒日期" clearable ></DatePicker>
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="提醒状态" prop="insuranceWhetherRemind">
                <i-switch v-model.number="formData.insuranceWhetherRemind" :false-value="0" :true-value="1">
                  <span slot="open">开</span>
                  <span slot="close">关</span>
                </i-switch>
              </FormItem>
            </i-col>
          </i-col>

          <i-col span="24">
            <FormItem label="附件上传">
              <Upload name="insurancePolicyPdfFile" :before-upload="insurancePolicyPdfFileFun" action="" style="display: inline-block;">
                <Button type="primary">选择要上传的件（pdf格式文件）</Button>
              </Upload>
              {{insurancePolicyPdfFileData.name}}
            </FormItem>
          </i-col>

          <i-col span="24">
            <FormItem label="保险资料">
              <Upload action="*" :show-upload-list="false" :format="['jpg','jpeg','png']" :before-upload="handleBeforeUpload" multiple>
                <Button icon="ios-cloud-upload-outline">选择要上传的图片</Button>
              </Upload>
              <div style="margin:10px 0 0 0;padding: 10px;min-height: 220px;border: 1px solid #e1e1e1;">
                <div style="width: 200px;overflow: hidden;display: inline-block;margin-right: 4px;" v-for="item,index in imgEntityList">
                  <div class="_wz_insertimage">
                    <img :src="!!item.insuranceImgUrl?apiUrl.imgUrl+item.insuranceImgUrl:''" @error="public.imgDispose" />
                    <div class="_wz_insertimage-cover" v-if="!!item.insuranceImgUrl">
                      <Icon type="ios-eye-outline" @click.native="handleView(apiUrl.imgUrl+item.insuranceImgUrl)"></Icon>
                      <Icon type="ios-trash-outline" @click.native="imgEntityListRemove(item,index)"></Icon>
                    </div>
                  </div>
                  <i-input v-model="item.insuranceImgDescribe" placeholder="填写图片名称" @on-change="alterImgName(item)" clearable />
                </div>

                <div style="width: 200px;overflow: hidden;display: inline-block;margin-right: 4px;" v-for="item,index in defaultList">
                  <div class="_wz_insertimage">
                    <img :src="item" @error="public.imgDispose">
                    <div class="_wz_insertimage-cover">
                      <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
                      <Icon type="ios-trash-outline" @click.native="handleRemove(item,index)"></Icon>
                    </div>
                  </div>
                  <i-input v-model="nameList[index]" placeholder="填写图片名称" clearable />
                </div>
              </div>
            </FormItem>
          </i-col>
          <i-col span="24">
            <FormItem label="备注" prop="insuranceRemark">
              <i-input v-model="formData.insuranceRemark" placeholder="请填写备注" type="textarea" :autosize="{minRows: 5,maxRows: 5}" />
            </FormItem>
          </i-col>
        </Row>
      </Card>
      <div class="demo-drawer-footer">
        <Button style="margin-right: 8px" @click="$emit('closeFun', false)">取消</Button>
        <Button type="primary" @click="addSubmit('formAdd')">提交</Button>
      </div>
    </Form>


    <!--图片查看-->
    <Modal title="图片查看" v-model="visible">
      <img :src="imgSrc" v-if="visible" style="width: 100%" @error="public.imgDispose" />
    </Modal>

  </div>
</template>
<script>
  import vehicleBriefly from '../expire/vehicleBriefly.vue'

  export default {
    components: {
      vehicleBriefly,//车辆基本信息
    },
    props: ["selectData"],//接收来自父组件的数据
    data() {
      return {

        defaultList: [],//图片展示数据
        defaultListData: [],//图片表单数据

        nameList: [],//图片名称
        imgEntityList: [],//多图回显数据
        //缩略图
        visible: false,
        imgSrc: "",


        beginTime: {},//开始时间
        endTime: {},//结束时间

        uploadProgress: 0,//文件上传进度
        vehicleBrieflyData: {},

        insurancePolicyPdfFileData: {
          data: null,//附件上传
          name: ''
        },
        carList: [],//车和挂车List
        insuranceCompany:[],//保险公司
        insuranceType:[],//企业保险字典
        formData: {},//新增修改表单数据

        ruleValidate: {//正则
          insuranceModelType: [
            {type: 'number',required: true, message: '请选择保险车型', trigger: 'blur'},
          ],
          insuranceRemindDay:[
            {type: 'number', required: true, message: '请填写提醒天数', trigger: 'blur'}
          ],
          wzInsuranceRemindDate: [
            {type: "date", required: true, message: "请选择提醒日期", trigger: "blur"}
          ],

          refVehicleTrailerUuid: [
            {required: true, message: '请选择保险车辆', trigger: 'blur'},
          ],
          insuranceTypeValue: [
            {required: true, message: '请选择保险项目', trigger: 'blur'}
          ],
          insuranceCompanyValue: [
            {required: true, message: '请填写保险公司', trigger: 'blur'}
          ],
          wzInsuranceDate:[
            {type: "date", required: true, message: '请选择办理时间', trigger: 'blur'}
          ],
          wzInsuranceEffectiveDate:[
            {type: "date", required: true, message: '请选择生效日期', trigger: 'blur'}
          ],
          wzInsuranceExpireDate:[
            {type: "date", required: true, message: '请选择到期日期', trigger: 'blur'}
          ],
          insuranceRegistrantName: [
            {required: true, message: '请填写登记人', trigger: 'blur'}
          ],
          insuranceVehicleTrailerOwnerName: [
            {required: true, message: '请填写车主业户', trigger: 'blur'},
          ],
          insuranceVehicleTrailerOwnerPhone: [
            {required: true, message: '请填写联系电话', trigger: 'blur'},
            {
              validator: (rule, value, callBack) => {
                if (/^[1][0-9]{10}$/.test(value) || /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(value)) {
                  callBack()
                } else {
                  callBack('请输入手机号 或者 区号-座机号')
                }
              }, trigger: 'blur'
            }
          ],
        },
      }
    },
    computed: {//计算属性
      vehicle: function () {
        // 通过vuex的getters方法来获取state里面的数据
        return this.$store.getters.getVehicle;
      }
    },
    beforeCreate() {//beforeCreate创建前状态

    },
    created() {//created创建完毕状态

    },
    beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

    },
    mounted() {//mounted 挂载结束状态
      let that = this;


      if (!!that.selectData.id) {
        that.axios.post(that.apiUrl.webApi + "/management/insurance/insuranceInfo",  {uuid: that.selectData.uuid}).then(res => {
          if (!!res) {
            var formData = res.data.data;
            that.insuranceModelTypeFun({value: formData.insuranceModelType});
            that.insuranceVehicleTrailerPlateNoFun({
              value: formData.refVehicleTrailerUuid,
              label: formData.insuranceVehicleTrailerPlateNo
            });
            //办理时间
            formData.wzInsuranceDate = new Date(formData.insuranceDate);
            //续保日期

            formData.wzInsuranceEffectiveDate = new Date(formData.insuranceEffectiveDate);
            //到期日期
            formData.wzInsuranceExpireDate = new Date(formData.insuranceExpireDate);

            formData.wzInsuranceRemindDate = !!new Date(formData.insuranceRemindDate)?new Date(formData.insuranceRemindDate):'';

            let imgList = [];
            res.data.data.imgEntityList.forEach((k, i) => {
              k.imgUrl = that.apiUrl.imgUrl + k.insuranceImgUrl
              imgList.push(k);
            })

            that.imgEntityList = imgList;//res.data.data.imgEntityList;//多图回显
            formData.imgUpdateListStr = [];
            formData.imgDeleteIdListStr = [];

            //车辆简述
            that.vehicleBrieflyData = {
              modelType: formData.insuranceModelType,
              value: formData.refVehicleTrailerUuid
            };

            that.formData = formData;
            // that.onBeginTime();
            // that.onEndTime();

          }
        }).catch(err => {
          console.log("失败", err)
        });


      }else{
        that.formData = {
          insuranceRemindDay:90,
          insuranceWhetherRemind:1,
          insuranceVehicleTrailerOwnerName: '',//车主业户
          insuranceVehicleTrailerOwnerPhone: '',//联系电话
          insuranceRegistrantName:JSON.parse(sessionStorage.getItem('loginData')).user.name,
          wzInsuranceDate:new Date(),
          wzInsuranceEffectiveDate:new Date(),
          wzInsuranceExpireDate:'',
          wzInsuranceRemindDate:''
        }
        let date = new Date();
        date.setFullYear(date.getFullYear() + 1);
        that.formData.wzInsuranceExpireDate = date;
        that.wzInsuranceRemindDateFun();
      }


      //企业自己保险字典
      that.axios.post(that.apiUrl.webApi + "/core/dept/dict/coreDeptDictList",  {type: 'insurance_type'}).then(res => {
        if (!!res) {
          that.insuranceType = res.data.data;
        }
      }).catch(err => {
        console.log("失败", err)
      });
      //企业自己保险公司字典
      that.axios.post(that.apiUrl.webApi + "/core/dept/dict/coreDeptDictList",  {type: 'insurance_company'}).then(res => {
        if (!!res) {
          that.insuranceCompany = res.data.data;
        }
      }).catch(err => {
        console.log("失败", err)
      });

    },
    methods: {//执行的方法
      //提醒时间
      wzInsuranceRemindDateFun(){
        var that = this;
        if (/^-?[1-9]\d*$/.test(that.formData.insuranceRemindDay) && !!that.formData.wzInsuranceExpireDate) {
          //确定 是数字 进行计算
          that.$nextTick(function () {
            that.formData.wzInsuranceRemindDate = new Date(new Date(that.formData.wzInsuranceExpireDate).getTime() - parseInt(that.formData.insuranceRemindDay) * 24 * 60 * 60 * 1000);
          })
        }else{
          that.formData.wzInsuranceRemindDate = '';
        }
      },
      //保险公司追加
      insuranceCompanyFun(data){
        var that = this;
        //企业自己保险字典
        var obj = {
          type: "insurance_company",
          name: "投保公司",
          value: data
        }
        that.insuranceCompany.push({
          value: data,
          label: data
        })
        that.axios.post(that.apiUrl.coreDeptDictCoreDeptDictSaveOrUpdate,  obj);
      },
      //险种追加
      additionalInsuranceFun(data){
        var that = this;
        //企业自己保险字典
        var obj = {
          type: "insurance_type",
          name: "保险险种",
          value: data
        }
        that.insuranceType.push({
          value: data,
          label: data
        })
        that.axios.post(that.apiUrl.coreDeptDictCoreDeptDictSaveOrUpdate,  obj);
      },
      //开始时间
      onBeginTime(startTime, type) {
        let that = this;
        that.wzInsuranceRemindDateFun();
        that.endTime = {
          disabledDate(endTime) {
            return endTime < new Date(that.formData.wzInsuranceEffectiveDate) //|| endTime > Date.now()
          }
        }

        //if (!!!that.formData.wzInsuranceExpireDate) {//如果没有到期时间 赋值一年后到期
        let date = new Date(startTime);
        date.setFullYear(date.getFullYear() + 1);
        that.formData.wzInsuranceExpireDate = date;
        //}
      },
      //结束时间
      onEndTime() {
        let that = this;
        that.wzInsuranceRemindDateFun();
        that.beginTime = {
          disabledDate(startTime) {
            return startTime > new Date(that.formData.wzInsuranceExpireDate) //|| startTime > Date.now()
          }
        }
      },
      //附件上传
      insurancePolicyPdfFileFun(file) {
        let that = this;
        let name = file.name.substr((file.name.lastIndexOf(".") + 1));
        if (name == 'pdf' || name == 'PDF') {
          that.insurancePolicyPdfFileData = {
            data: file,
            name: file.name
          }
        } else {
          that.$Message.error('请选择pdf的文件进行上传');
        }
        return false;
      },


      addSubmit(name) {//新增修改提交
        let that = this;
        that.$refs[name].validate((valid) => {
          if (valid) {//正则判断使用
            let data = that.formData;
            let formData = new FormData();


            //办理时间
            data.insuranceDate = !!data.wzInsuranceDate ? that.public.timeFormatting(data.wzInsuranceDate, "yyyy-MM-dd") : '';
            //续保日期
            data.insuranceEffectiveDate = !!data.wzInsuranceEffectiveDate ? that.public.timeFormatting(data.wzInsuranceEffectiveDate, "yyyy-MM-dd") : '';
            //到期日期
            data.insuranceExpireDate = !!data.wzInsuranceExpireDate ? that.public.timeFormatting(data.wzInsuranceExpireDate, "yyyy-MM-dd") : '';

            // //保险年份
             data.insuranceYearNumber = !!data.wzInsuranceEffectiveDate ? that.public.timeFormatting(!!data.wzInsuranceEffectiveDate, "yyyy") : '';


            data.insuranceRemindDate = that.public.timeFormatting(data.wzInsuranceRemindDate, "yyyy-MM-dd");

            //附件上传
            !!that.insurancePolicyPdfFileData.data ? formData.append('insurancePolicyPdfFile', that.insurancePolicyPdfFileData.data) : "";


            //年检资料
            that.defaultListData.forEach(function (k, i) {
              let type = k.name.substr((k.name.lastIndexOf(".") + 1));
              formData.append('imgList', k, (that.nameList[i].length > 0 ? that.nameList[i] : '图片描述') + '.' + type);
            })

            if (!!data.imgUpdateListStr) {
              if (data.imgUpdateListStr instanceof Object) {
                data.imgUpdateListStr = JSON.stringify(data.imgUpdateListStr);
              }
            }

            //修改提交删除字段
            delete data.imgEntityList;


            for (let key in data) {
              // if (!!data[key]) {
                formData.append(key, data[key]);
              // }
            }
            that.axios.post(that.apiUrl.webApi + "/management/insurance/insuranceSaveOrUpdate", formData,that.public.parameterUploadProgress(that)).then(res => {
              that.$Spin.hide();
              if (!!res) {
                that.$Message.success("保存成功");
                that.$emit("closeFun", true)
              }
            }).catch(err => {
              console.log('失败', err);
            })
          } else {
            this.$Message.error('请正确填写表单');
          }
        })
      },
      //保险车型 查询对应的车 还是挂车list
      insuranceModelTypeFun(e) {
        let that = this;
        if (!!e) {
          if (e.value == 1) {//车辆
            that.axios.post(that.apiUrl.webApi + "/core/vehicle/coreVehicleList", {}).then(res => {
              if (!!res) {
                that.carList = res.data.data;
              }
            }).catch(err => {
              console.log('失败', err);
            })
          } else {//挂车
            that.axios.post(that.apiUrl.webApi + "/core/trailer/coreTrailerList",{}).then(res => {
              if (!!res) {
                that.carList = res.data.data;
              }
            }).catch(err => {
              console.log('失败', err);
            })
          }
        } else {//清空数据
          //清空 保险车牌   //清空 车数据
          that.carList = [];
        }
      },
      //保险车牌号
      insuranceVehicleTrailerPlateNoFun(e) {
        let that = this;
        if (!!e) {
          that.formData.insuranceVehicleTrailerPlateNo = e.label;
        } else {
          that.formData.insuranceVehicleTrailerPlateNo = '';
        }
        e = !!e ? e : {};
        if (!!that.formData.insuranceModelType) {
          e.modelType = that.formData.insuranceModelType;
        }
        that.vehicleBrieflyData = e;
      },

      //保险资料删除
      handleRemove(file, index) {//新添加的图片删除
        this.defaultList.splice(index, 1);
        this.defaultListData.splice(index, 1);
        this.nameList.splice(index, 1);
      },
      //多图回显删除
      imgEntityListRemove(data, index) {
        this.formData.imgDeleteIdListStr.push(data.uuid);
        this.imgEntityList.splice(index, 1);
      },
      alterImgName(data) {
        let that = this;
        let type = true;
        that.formData.imgUpdateListStr.forEach((k, i) => {
          if (k.uuid == data.uuid) {//存在相同数据
            k.insuranceImgDescribe = (data.insuranceImgDescribe.length > 0 ? data.insuranceImgDescribe : "图片描述");
            type = false;
            return false;
          }
        })
        if (type) {
          that.formData.imgUpdateListStr.push({
            'uuid': data.uuid,
            insuranceImgDescribe: (data.insuranceImgDescribe.length > 0 ? data.insuranceImgDescribe : "图片描述")
          });
        }
      },
      //缩略图查看
      handleView(src) {
        // const viewer = this.$el.querySelector('._wz_insertimage').Viewer
        // viewer.show()
        this.imgSrc = src;
        this.visible = true;
      },
      //保险资料
      handleBeforeUpload(file) {//新增的时候 处理图片数据
        //如果是文件  就展示文件名
        let type = file.type.split("/")[0];
        if (type == "image") {//图片
          this.defaultList.push(window.URL.createObjectURL(file));
          this.defaultListData.push(file);
          this.nameList.push("图片描述");
        } else {
          this.$Message.error('请选择jpg、png、jpeg的图片进行上传');
        }
        return false;
      },
    },
    watch: {//监听
      vehicle(news, old) {
        if (!this.selectData.id) {
          this.formData.insuranceVehicleTrailerOwnerName = news.wzVehicleOwnerName;
          this.formData.insuranceVehicleTrailerOwnerPhone = news.wzVehicleOwnerPhone;
        }
      }
    },
    beforeUpdate() {//beforeUpdate 更新前状态

    },
    updated() {//updated 更新完成状态

    },
    beforeDestroy() {//beforeDestroy 销毁前状态

    },
    destroyed() {//destroyed 销毁完成状态

    }
  }
</script>
<style lang="less">
  ._wz_insuranceAdd {
    padding: 0 0 53px 0;

    .demo-upload-list {
      display: inline-block;
      width: 200px;
      height: 140px;
      text-align: center;
      line-height: 140px;
      border-radius: 4px;
      overflow: hidden;
      background: #fff;
      position: relative;
      border: 1px solid rgba(0, 0, 0, .2);
      margin-right: 4px;

      img {
        width: 100%;
        height: 100%;
      }

      .demo-upload-list-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, .6);

        i {
          color: #fff;
          font-size: 40px;
          cursor: pointer;
          margin: 0 2px;
        }
      }
    }

    .demo-upload-list:hover .demo-upload-list-cover {
      display: block;
    }
  }

</style>
